package band.wukong.practice.webservice.kh.sample05;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import javax.xml.ws.soap.SOAPFaultException;
import java.util.Set;

/**
 * Lisence handler primally
 *
 * @author wukong(wukonggg@139.com)
 */
public class JukeboxServerHeaderHandlerPrimally implements SOAPHandler<SOAPMessageContext> {

    @Override
    public Set<QName> getHeaders() {
        return null;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        System.out.println("[Server][Handler] handleMessage");

        // 对于server，如果out是true，说明消息是要发送出去的，不需要处理header；
        // 对于server，如果out是false，说明消息是接收进来的，需要处理header。
        Boolean out = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (out) {
            return true;
        }

        SOAPMessage message = context.getMessage();
        try {
            SOAPEnvelope envelope = message.getSOAPPart().getEnvelope();
            SOAPHeader header = envelope.getHeader();

            // -------- video21之前不需要这段, video21加的 ------------
            if (null == header || !header.extractAllHeaderElements().hasNext()) {
                SOAPBody body = envelope.getBody();
                SOAPFault fault = body.addFault();
                fault.setFaultCode("ERR_666");
                fault.setFaultString("没有header信息");
                throw new SOAPFaultException(fault);
            }
            // -------- video21之前不需要这段, video21加的 ------------

            NodeList nodeList = header.getElementsByTagName("ns:licenseInfo");
            Node node = nodeList.item(0);
            System.out.println("[Server][Handler] " + node.getTextContent());

        } catch (SOAPException e) {
            e.printStackTrace();
        }

        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        System.out.println("[Server][Handler] handleFault");
        return false;
    }

    @Override
    public void close(MessageContext context) {
        System.out.println("[Server][Handler] close");
    }
}
